package com.weim.weim.base;

import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Setter
@Getter
public class ApiResponse<T> {
    private Integer code = StatusCode.OPERATION_SUCCESS.getCode();
    private String message;
    private T data;
    private String currentTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

    public static ApiResponse<?> ok() {
        return valueOf(StatusCode.OPERATION_SUCCESS.getCode(), null);
    }

    public static ApiResponse<?> valueOfParamsIllegal(String message) {
        return valueOf(StatusCode.PARAMS_ILLEGAL.getCode(), message);
    }

    public static ApiResponse<?> fail(String message) {
        return valueOf(StatusCode.OPERATION_FAILED.getCode(), message);
    }

    public static boolean isSuccess(ApiResponse<?> apiResponse) {
        return apiResponse != null && StatusCode.OPERATION_SUCCESS.getCode().equals(apiResponse.getCode());
    }

    public static <T> ApiResponse<T> ok(T data) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setData(data);
        return apiResponse;
    }

    public static ApiResponse<?> valueOf(int code, String message) {
        ApiResponse<?> apiResponse = new ApiResponse<>();
        apiResponse.setCode(code);
        apiResponse.setMessage(message);
        return apiResponse;
    }

    public static <T> ApiResponse<T> valueOf(int code, String message, T data) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setCode(code);
        apiResponse.setMessage(message);
        apiResponse.setData(data);
        return apiResponse;
    }

    public static ApiResponse<?> needLogin() {
        return ApiResponse.valueOf(StatusCode.NEED_LOGIN.getCode(), StatusCode.NEED_LOGIN.getMessage());
    }

    public static <T> ApiResponse<T> needLogin(T data) {
        return ApiResponse.valueOf(StatusCode.NEED_LOGIN.getCode(), StatusCode.NEED_LOGIN.getMessage(), data);
    }


    public static ApiResponse<?> noPrivilege() {
        return ApiResponse.valueOf(StatusCode.NO_PRIVILEGE.getCode(), StatusCode.NO_PRIVILEGE.getMessage());
    }


    @Override
    public String toString() {
        return toString(false);
    }

    public String toString(boolean prettyFormat) {
        return JSON.toJSONString(this);
    }
}
